using System;
using System.Linq;
using Demo.Db;
using Demo.Models;
using Microsoft.EntityFrameworkCore;

namespace Demo.Repository
{
    public class EfRepository<T> : IRepository<T> where T : BaseEntity
    {
        private readonly DemoFirst _db;
        private readonly DbSet<T> _table;
        public IQueryable<T> table 
        {
            get
            {
                 return _table.AsQueryable<T>();
            }
        }
        public EfRepository()
        {
            _db = new DemoFirst();
            _table = _db.Set<T>();
        }
        public void Delete(int Id)
        {
            var entity = _table.Where(x=>x.Id ==Id).FirstOrDefault();
            entity.IsDeleted = true;
            entity.UpdateTime = DateTime.Now;
            _table.Update(entity);
            _db.SaveChanges();
        }

        public void Insert(T entity)
        {
            entity.IsActived = true;
            entity.IsDeleted = false;
            entity.CreateTime = DateTime.Now;
            entity.UpdateTime = DateTime.Now;
            entity.DisplayOrder = entity.DisplayOrder!=0?entity.DisplayOrder:0;
            _table.Add(entity);
            _db.SaveChanges();
        }

        public void Update(T entity)
        {
            entity.UpdateTime = DateTime.Now;
            _table.Update(entity);
            _db.SaveChanges();
        }
    }
}